package com.heyxampis.newmantis.util.utilitarios;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.ParameterizedType;
import java.net.MalformedURLException;
import java.util.Collection;
import java.util.Map;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import net.sf.jasperreports.engine.export.JRPdfExporter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

public class GerarRelatorio<T> {
	
	private static final Log LOG = LogFactory.getLog(GerarRelatorio.class);
	
	// Classe que ser� persistida.
		private Class<T> persistentClass;

		public Class<T> getPersistentClass() {
			return this.persistentClass;
		}
	
	@SuppressWarnings("unchecked")
	public GerarRelatorio(){
		this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}
	
//	public void gerar(String localRelatorio, Map<String, Object> parametros , Collection<T> lista) throws MalformedURLException{
//		
//		ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
//        ServletContext contextS = (ServletContext) externalContext.getContext();
//		
//		ServletOutputStream servletOutputStream = null;
//        FacesContext context = FacesContext.getCurrentInstance();
//        HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();
//        String arquivo = contextS.getRealPath("/WEB-INF/classes/br/com/IsoErp/relatorios/" + localRelatorio);
//		
//		try {
//			
//			servletOutputStream = response.getOutputStream();
//			
//		    JasperRunManager.runReportToPdfStream(new FileInputStream(new File(arquivo)), response.getOutputStream(), parametros, new JRBeanCollectionDataSource(lista));
//			
//		    response.setContentType("application/pdf");
//            servletOutputStream.flush();
//            servletOutputStream.close();
//            context.renderResponse();
//            context.responseComplete();
//		    
//		} catch (JRException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//	}
	
		public StreamedContent gerar(String localRelatorio, Map<String, Object> parametros , Collection<T> lista, String nomeArquivoSaida) throws MalformedURLException{
		
		InputStream relatorio = null;  
		ByteArrayOutputStream relat = new ByteArrayOutputStream(); 	
		ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
	    ServletContext contextS = (ServletContext) externalContext.getContext();
	    String arquivo = contextS.getRealPath("/relatorios/" + localRelatorio);
		try {
			
			JasperPrint print = JasperFillManager.fillReport(new FileInputStream(new File(arquivo)), parametros, new JRBeanCollectionDataSource(lista));
			JRExporter exporter = new JRPdfExporter();
			exporter.setParameter(JRExporterParameter.JASPER_PRINT, print);
			exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, relat);
			exporter.exportReport();
			relatorio = new ByteArrayInputStream(relat.toByteArray());
		    
		} catch (JRException e) {
			LOG.error(e.getMessage(), e);
			e.printStackTrace();
		} catch (IOException e) {
			LOG.error(e.getMessage(), e);
			e.printStackTrace();
		} catch (Exception e){
			LOG.error(e.getMessage(), e);
		}
		
		return new DefaultStreamedContent(relatorio, "application/pdf", nomeArquivoSaida + ".pdf");
		
	}

}
